from . import app_weixin_pay
from .conn_mysql import ConnectMysql
from .setting import config
from flask import request
from datetime import datetime, timedelta
from flask import Flask, jsonify, request, url_for
from weixin import Weixin, WeixinError



weixin = Weixin(config)

@app_weixin_pay.route("/jsapi")
def pay_jsapi():
    """微信网页支付请求发起"""
    openid = request.args.get('openid')
    body = request.args.get('body')
    total_fee = request.args.get('total_fee')
    
    if not all((openid, body, total_fee)):

        return {
                'status': -1,
                'errorCode': '1002',
                'errorMsg': '参数没有到位',
                'resultBody': None
            }

    try:

        out_trade_no = weixin.nonce_str
        raw = weixin.jsapi(openid=openid, body=body, out_trade_no=out_trade_no, total_fee=total_fee)
        
        #定单入库
        conn_obj = ConnectMysql()#链接数据库
        sql = 'insert into prepay(prepay_id, openid, body, total_fee) values (%s,%s,%s,%s)'
        conn_obj.insert_info(
            sql, 

            (
                raw['package'].replace('prepay_id=', ''),
                openid, 
                body, 
                total_fee
            )
        )
        conn_obj.close()
        
        return jsonify(
            {
                'status': 1,
                'errorCode': None,
                'errorMsg': None,
                'resultBody': raw
            }
        )
    except WeixinError as e:
        
        return {
                'status': -1,
                'errorCode': '1003',
                'errorMsg': e.args[0],
                'resultBody': None
            }


@app_weixin_pay.route("/notify")
def pay_notify():
    """
    微信异步通知
    """
    conn_obj = ConnectMysql()#链接数据库
    data = weixin.to_dict(request.data)
    prepay_id = data.get('prepay_id')
    sql_prepay_status = 'UPDATE prepay SET status=%s WHERE preapy_id=%s'

    #{'return_code': 'SUCCESS', 'return_msg': 'OK', 'appid': 'wx2421b1c4370ec43b', 'mch_id': '10000100', 'nonce_str': 'IITRi8Iabbblz1Jc', 'openid': 'oUpF8uMuAJO_M2pxb1Q9zNjWeS6o', 'sign': '7921E432F65EB8ED0CE9755F0E86D72F', 'result_code': 'SUCCESS', 'prepay_id': 'wx201411101639507cbf6ffd8b0779950874', 'trade_type': 'JSAPI'}
    if not weixin.check(data):
        conn_obj.update_info(sql_prepay_status, ('FLASE', prepay_id))#更改定单状态为失败
        conn_obj.close()
        return weixin.reply("签名验证失败", False)

    
    # 处理业务逻辑
    # 定单处理
    conn_obj.update_info(sql_prepay_status, (data['result_code'], prepay_id))#更改定单新动态
    # conn_obj.insert_info(sql, (data['prepay_id'], data['openid'], data['result_code']))
    conn_obj.close()
    if data['result_code'] == 'SUCCESS':

        sql = 'SELECT * FROM prepay WHERE prepay_id=%s'

        info = conn_obj.select_one(sql, (prepay_id,))

        total_fee = int(info.get('total_fee'))

        if total_fee == 30:

            add = 1
        if total_fee == 100:

            add = 4

        if total_fee == 200:

            add = 10

        up_sql = "UPDATE company SET consumption_surplus=consumption_surplus+%s"

        conn_obj.update_info(up_sql, (add,))

        conn_obj.close()

        return weixin.reply("OK", True)

    
    return weixin.reply("OK", True)


    